<template>
  <div class="el-upload">
    <el-upload
      v-if="showButton"
      class="upload-demo"
      :accept="supportZip ? '.rar,.zip,.doc,.docx,.pdf' : '.doc,.docx,.pdf'"
      :action="uploadUrl"
      multiple
      :headers="myHeaders"
      :on-success="uploadSuccess"
      :before-upload="beforeUpload"
      :show-file-list="false"
    >
      <div class="createBtn">
        <img src="@/assets/images/choice.png" alt="" />
        {{ $t("common.upload") }}
      </div>
      <template #tip>
        <div class="el-upload__tip" style="width: 80%">
          {{
            supportZip ? $t("common.uploadTipsZip") : $t("common.uploadTips")
          }}
        </div>
      </template>
    </el-upload>
    <el-progress
      v-if="isUpload"
      status="success"
      :percentage="100"
      :format="format"
      :indeterminate="true"
      style="width: 80%"
    />
    <div v-if="fileList.length > 0" class="fileList">
      <div
        v-for="(file, index) in fileList"
        :key="file.createTime"
        class="listItem"
        :class="{ fullWidth: isFull }"
        @click.stop="downloadFile(file.url, file.fileName, file.fileExtension)"
      >
        <el-tooltip
          class="box-item"
          effect="dark"
          :disabled="file.fileName.length < 10"
          :content="`${file.fileName}.${file.fileExtension}`"
          placement="top"
        >
          <div class="fileName">
            {{ file.fileName + "." + file.fileExtension }}
          </div>
        </el-tooltip>

        <div class="fileSize">
          <span>{{ file.createTime }}</span>
          <span>
            <span v-if="file.fileSize / 1024 > 1"
              >{{ (file.fileSize / 1024).toFixed(2) }} MB</span
            ><span v-else>{{ file.fileSize.toFixed(2) }} KB</span>
          </span>
        </div>
        <div
          v-if="isCanDelete"
          class="delete"
          @click.stop="deleteFile(index, file.fileId)"
        ></div>
      </div>
    </div>
    <div v-if="fileList.length === 0" class="fileList">
      {{ $t("common.noUpload") }}
    </div>
  </div>
</template>

<script>
export default {
  name: "Upload",
};
</script>

<script setup>
import { defineProps } from "vue";
import { getToken } from "@/utils/auth";
import { download } from "@/api/airSpace/enquiry";
import { ElMessage, ElProgress } from "element-plus";
import { getCurrentInstance } from "vue";
const { $t } = getCurrentInstance().proxy;

const emits = defineEmits(["success", "deleteFile"]);
const { proxy } = getCurrentInstance();

const isUpload = ref(false);

const props = defineProps({
  fileList: {
    type: Array,
    default() {
      return [];
    },
  },
  uploadUrl: {
    type: String,
    default: import.meta.env.VITE_APP_BASE_API + "/file/upload",
  },
  myHeaders: {
    type: Object,
    default: {
      Authorization: "Bearer " + getToken(),
    },
  },
  isCanDelete: {
    type: Boolean,
    default: false,
  },
  showButton: {
    type: Boolean,
    default: false,
  },
  isFull: {
    type: Boolean,
    default: false,
  },
  supportZip: {
    type: Boolean,
    default: false,
  },
});

const typeList = props.supportZip
  ? [
      "application/x-compressed",
      "application/x-zip-compressed",
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      "application/pdf",
      "application/msword",
    ]
  : [
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      "application/pdf",
      "application/msword",
    ];

const format = (percentage) =>
  percentage === 100 ? "上传中……" : `${percentage}%`;

const uploadSuccess = (res) => {
  const { data } = res;
  if (res.code === 200) {
    isUpload.value = false;
    ElMessage.success($t("common.UploadSuccess"));
    emits("success", data);
  } else {
    isUpload.value = false;
    proxy.$modal.msgError($t("common.UploadSuccess"));
  }
};

const deleteFile = (index, fileId) => {
  emits("deleteFile", index, fileId);
};

const downloadFile = async (url, fileName, fileExtension) => {
  const res = await download({ url });
  var debug = res;
  if (debug) {
    var elink = document.createElement("a");
    elink.download = fileName + "." + fileExtension;
    elink.style.display = "none";
    var blob = new Blob([debug], { type: "application/octet-stream" });
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    document.body.removeChild(elink);
  } else {
    this.$message.error($t("common.DownloadException"));
  }
};

function beforeUpload(file) {
  // console.log(props.fileList.length);
  const filetype = file.type;
  if (!typeList.includes(filetype)) {
    ElMessage.error(
      props.supportZip
        ? $t("common.FiletypeErrorZip")
        : $t("common.FiletypeError")
    );
    return false;
  }
  if (props.fileList.length > 4) {
    ElMessage.error($t("common.FileNumError"));
    return false;
  }
  const maxSize = 20 * 1024 * 1024; // 20MB
  const isValidSize = file.size <= maxSize;
  if (!isValidSize) {
    ElMessage.error($t("common.FilesizeError"));
    return false;
  }
  isUpload.value = true;
  return isValidSize;
}
</script>

<style lang="scss">
.el-upload {
  .demo-progress .el-progress--line {
    margin-bottom: 15px;
    width: 80%;
  }
}
</style>

<style scoped lang="scss">
.el-upload {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  position: relative;
  width: 100%;

  .createBtn {
    // position: absolute;
    display: flex;
    justify-content: space-around !important;
    align-items: center;
    padding: 10px 21px !important;
    width: 98px;
    height: 36px;
    font-size: 12px;
    box-sizing: border-box;
    border-radius: 4px;
    color: rgba(43, 193, 123, 1);
    background: rgba(51, 151, 255, 0.03);
    border: 1px solid rgba(43, 193, 123, 1);
    cursor: pointer;
    &:hover {
      background: rgba(51, 151, 255, 0.1);
    }
  }

  .fileList {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    width: 100%;

    .listItem {
      position: relative;
      margin-bottom: 5px;
      padding: 9px 20px;
      width: 80%;
      height: 65px;
      border-radius: 4px;
      background: rgb(245, 252, 249);

      .fileName {
        font-size: 14px;
        font-weight: 400;
        letter-spacing: 0px;
        line-height: 19.6px;
        color: rgba(56, 56, 56, 1);
        text-align: left;
        vertical-align: top;
        white-space: nowrap; /* 防止文本换行 */
        overflow: hidden; /* 超出部分隐藏 */
        text-overflow: ellipsis; /* 使用省略号隐藏 */
      }

      .fileSize {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 12px;
        font-weight: 400;
        letter-spacing: 0px;
        line-height: 30.8px;
        color: rgba(153, 153, 153, 1);
        text-align: left;
        vertical-align: top;
      }

      .delete {
        position: absolute;
        right: 10px;
        top: 10px;
        height: 14px;
        width: 14px;
        background: url("@/assets/images/delete.png");
      }
    }

    .fullWidth {
      width: 100%;
    }
  }
}
</style>
